package com.riteny.paymentgateway.swifypass.service;

import com.riteny.paymentgateway.swifypass.exception.SwiftPassPaymentGatewayException;
import com.riteny.paymentgateway.swifypass.entity.SwiftPassOrderSubmitParams;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author Riteny
 * 2021/7/1  11:26
 */
public class SwiftPassAliPayPaymentGatewayService extends AbstractSwiftPassPaymentGatewayService {

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");

    /**
     * 獲取支付寶支付的調用參數，XML格式
     *
     * @param params 支付網關參數，訂單參數等
     * @return XML 格式的 請求參數
     */
    @Override
    public Element getUnityOrderSubmitRequestXml(SwiftPassOrderSubmitParams params) {

        Date orderTime = new Date();

        Date orderExpireTime = new Date(System.currentTimeMillis() + (params.getOrderExpiredTime() * 1000));

        Document doc;
        try {
            doc = DocumentHelper.parseText("<xml>\n" +
                    "    <service>pay.alipay.app.intl</service>\n" +
                    "    <version>2.0</version>\n" +
                    "    <charset>UTF-8</charset>\n" +
                    "    <sign_type>SHA256</sign_type>\n" +
                    "    <mch_id>" + params.getPaymentGatewayMchId() + "</mch_id>\n" +
                    "    <out_trade_no>" + params.getOrderUuid() + "</out_trade_no>\n" +
                    "    <device_info>" + params.getDeviceId() + "</device_info>\n" +
                    "    <body>" + params.getBody() + "</body>\n" +
                    "    <total_fee>" + params.getTotalFee() + "</total_fee>\n" +
                    "    <mch_create_ip>127.0.0.1</mch_create_ip>\n" +
                    "    <payment_inst>ALIPAYHK</payment_inst>\n" +
                    "    <notify_url>" + params.getNotifyUrl() + "</notify_url>\n" +
                    "    <callback_url>http://127.0.0.1</callback_url>\n" +
                    "    <time_expire>" + simpleDateFormat.format(orderTime) + "</time_expire>\n" +
                    "    <time_start>" + simpleDateFormat.format(orderExpireTime) + "</time_start>\n" +
                    "    <op_user_id>" + params.getPaymentGatewayMchId() + "</op_user_id>\n" +
                    "    <nonce_str>" + params.getNonceStr() + "</nonce_str>\n" +
                    "</xml>");
        } catch (DocumentException e) {
            throw new SwiftPassPaymentGatewayException(SwiftPassPaymentGatewayException.UNKNOWN_ERROR, e.getMessage());
        }

        return doc.getRootElement();
    }

}
